<template>
  <view class="xiaoxiaole">
    <template v-if="!isShowAnswer">
      <view class="info">
        <view class="time">
          <text>计时：</text>
          <text>{{ minuteNumber }}:{{ secondNumber }}</text>
        </view>
        <view class="process">
          <text>{{ currentWordIndex + 1 }}/{{ wordNumber }}</text>
        </view>
      </view>
      <view class="options">
        <view
          class="options_content"
          v-for="(item, index) in wordArray"
          :key="index"
          @click="chooseOptions(item, index)"
        >
          <view
            class="options_img"
            v-if="item.word.length > 1"
            :class="{ active: item.isSelected }"
          >
            <image
              :src="
                'https://pc.abczxs.com/edcSystem/web/img/newimg/' +
                  item.word +
                  '.png'
              "
              mode="heightFix"
            ></image>
          </view>
          <view
            class="options_text"
            :class="{ active: item.isSelected }"
            v-else
          >
            <text>{{ item.word }}</text>
          </view>
        </view>
      </view>
      <view class="content">
        <view class="content_text">
          <text>{{ wordTest }}</text>
        </view>
        <view class="content_text">
          <input type="text" :disabled="true" v-model="answer" />
          <view class="content_icon" @click="deleteWord()">
            <u-icon name="close" color="#fff" size="32"></u-icon>
          </view>
        </view>
        <view class="content_text" @click="determine()">
          <text>确定</text>
        </view>
      </view>
    </template>
    <view class="word" v-else>
      <view class="word_container">
        <view class="word_content">
          <view class="word_title word_box">
            <view class="word_text"><text>中文</text></view>
            <view class="word_text"><text>正确答案</text></view>
            <view class="word_text"><text>你的答案</text></view>
            <view class="word_text"><text>结果</text></view>
          </view>
          <view
            class="word_box"
            v-for="(item, index) in wordList"
            :key="index"
          >
            <view class="word_text"
              ><text>{{ item.wordParaphrase }}</text></view
            >
            <view class="word_text"
              ><text>{{ item.word }}</text></view
            >
            <view class="word_text"
              ><text>{{ item.answer }}</text></view
            >
            <view class="word_text">
              <image
                v-if="item.isCorrect"
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/correct.png"
                mode="widthFix"
              ></image>
              <image
                v-else
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/error.png"
                mode="widthFix"
              ></image>
            </view>
          </view>
        </view>
      </view>
      <view class="word_button" @click="practiceAgain()">
        <image
          src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/game_button.png"
          mode="widthFix"
        ></image>
      </view>
    </view>
    <u-mask :show="isOver" :zoom="false" @click="isOver = false">
      <view class="popup_container">
        <view class="popup_content">
          <view class="popup_img" v-if="accuracy >= 80">
            <image
              src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/laugh.png"
              mode="widthFix"
            ></image>
          </view>
          <view class="popup_img" v-else>
            <image
              src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/cry.png"
              mode="widthFix"
            ></image>
          </view>
          <view class="popup_info">
            <view class="popup_info_con">
              <text>用时：</text><text>{{ countdown }}秒</text>
            </view>
            <view class="popup_info_con">
              <text>错误：</text><text>{{ wordNumber - correctNumber }}题</text>
            </view>
            <view class="popup_info_con">
              <text>正确：</text><text>{{ correctNumber }}题</text>
            </view>
            <view class="popup_info_con">
              <text>奖励金币：</text><text>{{ goldNum }}个</text>
            </view>
          </view>
        </view>
        <view class="popup_button" @click="viewDetails()">
          <image
            src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/game_button2.png"
            mode="widthFix"
          ></image>
        </view>
      </view>
    </u-mask>
  </view>
</template>
<script>
import { gameBonus } from "@/api/student";
import { arrayRandomly } from "@/libs/tools";
export default {
  name: "XiaoXiaoLe",
  props: {
    wordList: {
      type: Array,
      default: () => [],
    },
  },
  created() {
    this.init();
  },
  watch: {
    wordList() {
      if (this.isUpdate) {
        this.initData();
        this.init();
      }
    },
  },
  data() {
    return {
      wordTest: "",
      wordArray: [],
      wordNumber: 0,
      currentWordIndex: 0,
      wordAnswer: "",
      answer: "",
      answerIndex: [],
      minute: 3,
      minuteNumber: "03",
      second: 0,
      secondNumber: "00",
      countdown: 0,
      timerId: null,
      accuracy: 0,
      optionsImages: ["banma", "daxiang", "shizi", "shu", "tuzi", "xiong"],
      optionsNuber: 24,
      correctNumber: 0,
      goldNum: 0,
      audio: null,
      innerAudioContext: null,
      isPlaying: false,
      isOver: false,
      isShowAnswer: false,
    };
  },
  methods: {
    init() {
      this.wordNumber = this.wordList.length;
      this.initWord();
      this.timer();
      this.playAudio();
    },
    initWord() {
      this.wordTest = this.wordList[this.currentWordIndex].wordParaphrase;
      this.wordAnswer = this.wordList[this.currentWordIndex].word;
      let wordArray = this.wordAnswer.split("");
      for (let i = 0; wordArray.length < this.optionsNuber; i++) {
        wordArray.push(
          this.optionsImages[
            Math.floor(Math.random() * this.optionsImages.length)
          ]
        );
      }
      wordArray = arrayRandomly(wordArray);
      wordArray.forEach((item, index) => {
        this.wordArray.push({
          word: item,
          i: index,
          isSelected: false,
        });
      });
    },
    initData() {
      this.answer = "";
      this.currentWordIndex = 0;
      this.wordArray = [];
      this.goldNum = 0;
      this.minute = 3;
      this.minuteNumber = "03";
      this.second = 0;
      this.secondNumber = "00";
      this.countdown = 0;
      this.correctNumber = 0;
      this.goldNum = 0;
      this.isUpdate = false;
    },
    playAudio() {
      this.innerAudioContext = uni.createInnerAudioContext();
      this.innerAudioContext.autoplay = true;
      this.innerAudioContext.loop = true;
      this.innerAudioContext.src =
        "https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/audio/bg_music2.mp3";
      this.innerAudioContext.onPlay(() => {
        console.log("开始播放");
      });
      this.innerAudioContext.onError((res) => {
        console.log(res.errMsg);
        console.log(res.errCode);
      });
    },
    stopAudio() {
      this.innerAudioContext.stop();
    },
    chooseOptions(item, index) {
      if (item.word.length > 1) {
        this.$set(item, "isSelected", !item.isSelected);
      } else {
        if (item.isSelected) return;
        this.$set(item, "isSelected", true);
        this.answer += item.word;
        this.answerIndex.push(index);
      }
    },
    determine() {
      if (!this.answer) {
        uni.showToast({
          title: "答案不能为空！",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      if (this.answer === this.wordAnswer) {
        this.correctNumber++;
        this.wordList[this.currentWordIndex].answer = this.answer;
        this.wordList[this.currentWordIndex].isCorrect = true;
        this.play(true);
      } else {
        this.wordList[this.currentWordIndex].answer = this.answer;
        this.wordList[this.currentWordIndex].isCorrect = false;
        this.play(false);
      }
      if (this.currentWordIndex === this.wordList.length - 1) {
        this.gameOver();
        return;
      }
      this.answer = "";
      this.currentWordIndex++;
      this.wordArray = [];
      this.initWord();
    },
    gameOver() {
      clearInterval(this.timerId);
      this.accuracy = (
        ((this.correctNumber / this.wordNumber) * 10000) /
        100
      ).toFixed(2);
      if (this.accuracy >= 80) {
        this.goldNum = 1;
        this.addGold();
      }
      this.isOver = true;
    },
    play(flag) {
      if (this.isPlaying) return;
      this.audio = uni.createInnerAudioContext();
      this.audio.pause();
      if (flag) {
        this.audio.src =
          "https://pc.abczxs.com/edcSystem/web/videos/xxl-dc.mp3";
      } else {
        this.audio.src =
          "https://pc.abczxs.com/edcSystem/web/videos/xxl-dd.mp3";
      }
      this.audio.play();
      this.audio.onEnded(() => {
        this.isPlaying = false;
        this.innerAudioContext.play();
      });
      this.isPlaying = true;
    },
    timer() {
      this.timerId = setInterval(() => {
        this.second--;
        if (this.second < 0) {
          this.second = 59;
          this.minute--;
        }
        if (this.minute < 0) {
          this.gameOver();
          return;
        }
        if (this.second < 10) {
          this.secondNumber = this.second.toString().padStart(2, "0");
        } else {
          this.secondNumber = this.second.toString();
        }
        if (this.minute < 10) {
          this.minuteNumber = this.minute.toString().padStart(2, "0");
        } else {
          this.minuteNumber = this.minute.toString();
        }
        this.countdown++;
      }, 1000);
    },
    deleteWord() {
      if (!this.answer) return;
      this.answer = this.answer.substring(0, this.answer.length - 1);
      this.wordArray[
        this.answerIndex[this.answerIndex.length - 1]
      ].isSelected = false;
      this.answerIndex.pop();
    },
    viewDetails() {
      this.isShowAnswer = true;
      this.isOver = false;
    },
    practiceAgain() {
      this.isUpdate = true;
      this.isShowAnswer = false;
      this.$emit("init");
    },
    addGold() {
      gameBonus().then((res) => {
        this.goldNum = res.data.goldNum;
      });
    },
  },
};
</script>
<style scoped lang="scss">
@import "./XiaoXiaoLe";
</style>
